package com.fone.player.service;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.text.TextUtils;

import com.fone.player.ApplicationManage;
import com.fone.player.activity.main.MainTabActivity;
import com.fone.player.activity.main.SplashActivity;
import com.fone.player.activity.personal.NotificationActivity;
import com.fone.player.activity.personal.NotifyFeedBackActivity;
import com.fone.player.client.Reporter;
import com.fone.player.entity.NotificationBean;
import com.fone.player.play.PlayerAction;
import com.fone.player.play.PlayerFrom;
import com.fone.player.play.WebPlayerFrom;
import com.fone.player.storage.SharedPreferenceModule;
import com.fone.player.storage.StorageModule;
import com.fone.player.util.ActivityQueue;
import com.fone.player.util.FoneUtil;
import com.fone.player.util.L;
import com.fone.player.util.Notice2Online;

/**
 * 广播接收者
 * 
 * @author JasonZue
 * @since 2014-5-19
 */

public class NotificationReceiver extends BroadcastReceiver {

	private static final String TAG = "NotificationReceiver";
	public final static String NOTIFICATION_ISSTOP_FLAG = "isStop";
	public final static String NOTIFICATION_INFO = "notifcation_info";

	/* 广播Action类型 */
	public final static String NOTIFICATION_FULLSCREEN = "com.fone.player.notification.fullscreen";
	public final static String NOTIFICATION_DETAIL = "com.fone.player.notification.detail";
	public final static String NOTIFICATION_WAP = "com.fone.player.notification.wap"; // 打开wap网页
	public final static String NOTIFICATION_DOWNLOADSOFT = "com.fone.player.notification.downloadsoft"; // 软件下载
	public final static String NOTIFICATION_FEE = "com.fone.player.notification.fee"; // 计费流程
	public final static String NOTIFICATION_PROGRAM = "com.fone.player.notification.maintab.program";
	public final static String NOTIFICATION_WEB = "com.fone.player.notification.web";
	public final static String NOTIFICATION_FEEDBACK = "com.fone.player.notification.feedback";
	public final static String NOTIFICATION_NOTIFICATIONVIEW = "com.fone.player.notification.notificationview";
	public final static String NOTIFICATION_BOOK = "com.fone.player.notification.book";// 订阅通知
	public final static String NOTIFICATION_NOTIFICATION_CHECKSEND = "com.fone.player.notification.checksend";

	public final static String FROMNOTIFICATION = "from_notification";
	public final static String NOTIFICATIONTYPE = "notification_type";

	@Override
	public void onReceive(Context context, Intent intent) {

		SharedPreferences sp = context.getSharedPreferences("notificationService", Context.MODE_PRIVATE);
		boolean stop_flag = sp.getBoolean(NOTIFICATION_ISSTOP_FLAG, false);

		L.v(TAG, "onReceive", "action : " + intent.getAction());

		if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {

			// boot 开机启动
			if (!stop_flag && !isServiceStarted(context)) {
				FoneUtil.writeNotificationLog("通知服务没有运行,重新启动服务进程");
				FoneServiceManager.getFoneServiceManager(context).startNotificationService();
				L.v(TAG, "onReceive", "boot start notificationService");
				
				if (!stop_flag) {
					AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
					Intent i = new Intent("com.fone.notifyservice");
					PendingIntent pi = PendingIntent.getBroadcast(context, 11, i, PendingIntent.FLAG_UPDATE_CURRENT);
					am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 600000, pi);
				}
				
			}

			// 删除当前时间以前的节目单
			StorageModule.getInstance().deleteContentSubscribeByTime(System.currentTimeMillis());

		} else if (intent.getAction().equals(Intent.ACTION_USER_PRESENT) || intent.getAction().equals("android.net.conn.CONNECTIVITY_CHANGE") || intent.getAction().equals("android.net.conn.BACKGROUND_DATA_SETTING_CHANGED") || intent.getAction().equals("android.intent.action.BATTERY_CHANGED")
				|| intent.getAction().equals("android.intent.action.WALLPAPER_CHANGED")) {

			if (!stop_flag && !isServiceStarted(context)) {
				FoneUtil.writeNotificationLog("通知服务没有运行,重新启动服务进程");
				FoneServiceManager.getFoneServiceManager(context).startNotificationService();
				L.v(TAG, "onReceive", "boot end");
			}

		} else if (intent.getAction().equals(NOTIFICATION_DETAIL)) { // 详情页面

			L.v(TAG, "onReceive", "收到详情" + "queue size:" + ActivityQueue.getSize());

			// 判断网络
			if (!isNetOkWithNotification()) {
				return;
			}

			Reporter.logEvent(Reporter.EventId.NOTIC_OUTER_CLICK);// 点击上报

			// 跳转到详情页
			NotificationBean notificationBean = (NotificationBean) intent.getParcelableExtra(NotificationReceiver.NOTIFICATION_INFO);

			L.v(TAG, "onReceive", "" + notificationBean.getNotificationName() + " playUrl : " + notificationBean.getNotificationUrl());
			// 外通知到详情页需要添加参数ifp=23
			String url = notificationBean.getNotificationUrl();
			if (!TextUtils.isEmpty(url)) {
				url = url + "&ifp=23";
			}
			// 更改阅读状态
			notificationBean.setNotificationIsRead(true);

			if (notificationBean.getNotificationContentType() == NotificationBean.NOTIFICATION_CONTENT_TYPE_HOT_DRAMA) {
				FoneUtil.openOnlineVideo(context, PlayerFrom.NOTIFY_COLLECTION, PlayerAction.DETAIL, url, null, notificationBean.getNotificationDefinitionType(), null);
			} else {
				FoneUtil.openOnlineVideo(context, PlayerFrom.NOTIFICATION_EXTERNAL, PlayerAction.DETAIL, url, null, notificationBean.getNotificationDefinitionType(), null);
			}

			StorageModule.getInstance().updateNotificationIsRead(notificationBean);

		} else if (intent.getAction().equals(NOTIFICATION_FULLSCREEN)) { // 全屏页面

			L.v(TAG, "onReceive", "收到全屏" + "queue size:" + ActivityQueue.getSize());

			// 判断网络
			if (!isNetOkWithNotification()) {
				return;
			}

			Reporter.logEvent(Reporter.EventId.NOTIC_OUTER_CLICK);// 点击上报
			// 跳转到全屏页
			NotificationBean notificationBean = (NotificationBean) intent.getParcelableExtra(NotificationReceiver.NOTIFICATION_INFO);

			L.v(TAG, "onReceive", "NOTIFICATION_FULLSCREEN  playUrl : " + notificationBean.getNotificationUrl());
			// 更改阅读状态
			notificationBean.setNotificationIsRead(true);

			if (notificationBean.getNotificationContentType() == NotificationBean.NOTIFICATION_CONTENT_TYPE_HOT_DRAMA) {
				FoneUtil.openOnlineVideo(context, PlayerFrom.NOTIFY_COLLECTION, PlayerAction.FULLPLAY, null, notificationBean.getNotificationUrl(), notificationBean.getNotificationDefinitionType(), null);
			} else {
				FoneUtil.openOnlineVideo(context, PlayerFrom.NOTIFICATION_EXTERNAL, PlayerAction.FULLPLAY, null, notificationBean.getNotificationUrl(), notificationBean.getNotificationDefinitionType(), null);
			}

			StorageModule.getInstance().updateNotificationIsRead(notificationBean);

		} else if (intent.getAction().equals(NOTIFICATION_WEB)) { // 原网页

			L.v(TAG, "onReceive", "收到原网页" + "queue size:" + ActivityQueue.getSize());

			// 判断网络
			if (!isNetOkWithNotification()) {
				return;
			}

			Reporter.logEvent(Reporter.EventId.NOTIC_OUTER_CLICK);// 点击上报
			NotificationBean notificationBean = (NotificationBean) intent.getParcelableExtra(NotificationReceiver.NOTIFICATION_INFO);
			// 更改阅读状态
			notificationBean.setNotificationIsRead(true);
			FoneUtil.open3rdPlayer(context, WebPlayerFrom.NOTIFICATION, notificationBean.getNotificationExternalUrl(), notificationBean.getNotificationUrl(), null, notificationBean.getNotificationIsShowPlayButton() ? 1 : 0, notificationBean.getNotificationShareUrl(),notificationBean.getNotificationImageUrl());
			StorageModule.getInstance().updateNotificationIsRead(notificationBean);

		} else if (intent.getAction().equals(NOTIFICATION_FEEDBACK)) { // 反馈回复页

			L.v(TAG, "onReceive", "反馈回复" + "queue size:" + ActivityQueue.getSize());

			// 判断网络
			if (!isNetOkWithNotification()) {
				return;
			}

			Reporter.logEvent(Reporter.EventId.NOTIC_OUTER_CLICK);// 点击上报
			NotificationBean notificationBean = (NotificationBean) intent.getParcelableExtra(NotificationReceiver.NOTIFICATION_INFO);
			// 更改阅读状态
			notificationBean.setNotificationIsRead(true);
			StorageModule.getInstance().updateNotificationIsRead(notificationBean);

			Intent notificationIntent = new Intent(context.getApplicationContext(), NotifyFeedBackActivity.class);
			notificationIntent.putExtra(FROMNOTIFICATION, true);
			notificationIntent.putExtra(NotificationReceiver.NOTIFICATION_INFO, notificationBean);

			if (ActivityQueue.getSize() < 1) {
				notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				context.getApplicationContext().startActivity(notificationIntent);
			} else {
				// TODO 判断是否在前台
				if (!FoneUtil.isAppOnForeground(context)) {
					FoneUtil.wakeUpfromBackground(ActivityQueue.popIndex(0).getClass(), null);
				}
				ActivityQueue.popIndex(0).startActivity(notificationIntent);
			}

		} else if (intent.getAction().equals(NOTIFICATION_NOTIFICATIONVIEW)) { // 通知页
			L.v(TAG, "onReceive", "收到通知页" + "queue size:" + ActivityQueue.getSize());

			// 判断网络
			if (!isNetOkWithNotification()) {
				return;
			}

			Reporter.logEvent(Reporter.EventId.NOTIC_OUTER_CLICK);// 点击上报
			NotificationBean notificationBean = (NotificationBean) intent.getParcelableExtra(NotificationReceiver.NOTIFICATION_INFO);
			// 更改阅读状态
			notificationBean.setNotificationIsRead(true);
			StorageModule.getInstance().updateNotificationIsRead(notificationBean);

			Intent notificationIntent = new Intent(context.getApplicationContext(), NotificationActivity.class);
			notificationIntent.putExtra(FROMNOTIFICATION, true);
			notificationIntent.putExtra(NOTIFICATIONTYPE, notificationBean.getNotificationType());

			if (ActivityQueue.getSize() < 1) {
				notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				context.getApplicationContext().startActivity(notificationIntent);
			} else {
				// TODO 判断是否在前台
				if (!FoneUtil.isAppOnForeground(context)) {
					FoneUtil.wakeUpfromBackground(ActivityQueue.popIndex(0).getClass(), null);
				}
				ActivityQueue.popIndex(0).startActivity(notificationIntent);
			}

		} else if (intent.getAction().equals(NOTIFICATION_PROGRAM)) { // 栏目页

			L.v(TAG, "onReceive", "收到栏目" + "queue size:" + ActivityQueue.getSize());

			// 判断网络
			if (!isNetOkWithNotification()) {
				return;
			}

			Reporter.logEvent(Reporter.EventId.NOTIC_OUTER_CLICK);// 点击上报
			NotificationBean notificationBean = (NotificationBean) intent.getParcelableExtra(NotificationReceiver.NOTIFICATION_INFO);
			// 更改阅读状态
			notificationBean.setNotificationIsRead(true);
			StorageModule.getInstance().updateNotificationIsRead(notificationBean);

			// 跳转到栏目页面
			String columnUrl = notificationBean.getNotificationUrl();
			// columnUrl = "[host]/player/specllist?ifp=2&clid=41102";
			String columnName = notificationBean.getNotificationName();
			String cid = notificationBean.getNotificationServerId().substring(0, notificationBean.getNotificationServerId().indexOf("_"));
			Notice2Online.startActivity(context, true, columnUrl, columnName, cid, -1);

		} else if (intent.getAction().equals(NOTIFICATION_WAP)) { // wap页
			// TODO 调起网页
			L.v(TAG, "onReceive", "收到网页" + "queue size:" + ActivityQueue.getSize());

			// 判断网络
			if (!isNetOkWithNotification()) {
				return;
			}

			Reporter.logEvent(Reporter.EventId.NOTIC_OUTER_CLICK);// 点击上报
			NotificationBean notificationBean = (NotificationBean) intent.getParcelableExtra(NotificationReceiver.NOTIFICATION_INFO);
			// 更改阅读状态
			notificationBean.setNotificationIsRead(true);
			StorageModule.getInstance().updateNotificationIsRead(notificationBean);

			// 跳转到wap
			String webUrl = notificationBean.getNotificationUrl();
			String columnName = notificationBean.getNotificationName();
			String cid = notificationBean.getNotificationServerId().substring(0, notificationBean.getNotificationServerId().indexOf("_"));
			Notice2Online.startActivity(context, false, webUrl, columnName, cid, 34);

		} else if (intent.getAction().equals(NOTIFICATION_DOWNLOADSOFT)) { // 软件下载

			L.v(TAG, "onReceive", "收到软件下载" + "queue size:" + ActivityQueue.getSize());

			if (!stop_flag && !isServiceStarted(context)) {
				FoneServiceManager.getFoneServiceManager(context).startNotificationService();
			}

			// 判断网络
			if (!isNetOkWithNotification()) {
				return;
			}
			Reporter.logEvent(Reporter.EventId.NOTIC_OUTER_CLICK);// 点击上报

			// http://192.168.1.226:8084/venus_cms/upload/software/201405/19/20140519145158173/10.32.7.3245.8.8001.apk
			// NotificationBean notificationBean =
			// (NotificationBean)intent.getParcelableExtra(NotificationReceiver.NOTIFICATION_INFO);
			// //更改阅读状态
			// notificationBean.setNotificationIsRead(true);
			// StorageModule.getInstance().updateNotificationIsRead(notificationBean);

		} else if (intent.getAction().equals("com.fone.player.notification.update")) { // TODO 升级
																						// (不做)
		} else if (intent.getAction().equals(NOTIFICATION_FEE)) { // TODO 计费页
																	// (不做)
		} else if (intent.getAction().equals(NOTIFICATION_NOTIFICATION_CHECKSEND)) { // TODO
																						// 验证是否在通知页

			L.v(TAG, "onReceive", "是否在通知页" + "queue size:" + ActivityQueue.getSize());

			// 设置有新通知
			SharedPreferenceModule.getInstance().setBoolean(MainTabActivity.NEWNOTIFICATION, true);
			// 是否是通知页
			Activity current = ActivityQueue.popIndex(0);
			if (current != null) {
				if (current instanceof NotificationActivity) {

					// TODO 写入文件
					FoneUtil.writeNotificationLog("NotificationReceiver 收到广播, 当前页是通知列表页,不发送外通知");
					// TODO 是 刷新通知页
					ArrayList<NotificationBean> notificationList = intent.getParcelableArrayListExtra(NotificationReceiver.NOTIFICATION_INFO);
					int needReportNum = 0;
					for (NotificationBean notificationBean : notificationList) {
						notificationBean.setNotificationIsShow(true);
						int addNotification = StorageModule.getInstance().addNotification(notificationBean);
						L.v(TAG, "NotificationCallback  onSuccess ", " current is Notification  -------- " + addNotification);
						((NotificationActivity) current).refreshData(notificationBean.getNotificationType());

						if (notificationBean.getNotificationType() == NotificationBean.NOTIFICATION_TYPE && addNotification != -1) {
							needReportNum++;
						}
					}
					// TODO 上报内部通知
					FoneUtil.reportNotification(8, needReportNum, notificationList);
					abortBroadcast();// 中断广播
					return;
				} else if (current instanceof MainTabActivity) {// 当前页为我的视频页
																// 则更改通知标签
					((MainTabActivity) current).hasNewNotification();
				}
			}
			FoneUtil.writeNotificationLog("NotificationReceiver 收到广播, 没有在通知列表页 ,不拦截广播");
		} else if (intent.getAction().equals(NOTIFICATION_BOOK)) {// 订阅通知

			// 判断网络
			if (!isNetOkWithNotification()) {
				return;
			}

			// 跳转到详情页
			L.v(TAG, "onReceive", "NOTIFICATION_BOOK");
			FoneUtil.openOnlineVideo(context, PlayerFrom.NOTIFY_SUBSCRIBE, PlayerAction.DETAIL, intent.getStringExtra("vgdetail"), null, null, intent.getStringExtra("name"));
		} else if (intent.getAction().equals("com.fone.notifyservice")) {
			L.v(TAG, "onReceive", "com.fone.notifyservice");
			FoneUtil.writeNotificationLog("收到定时检查广播");
			if (!stop_flag && !isServiceStarted(context)) {
				FoneUtil.writeNotificationLog("定时检查 :  通知服务没有运行,重新启动服务进程");
				FoneServiceManager.getFoneServiceManager(context).startNotificationService();
			}
			if (!stop_flag) {
				AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
				Intent i = new Intent("com.fone.notifyservice");
				PendingIntent pi = PendingIntent.getBroadcast(context, 11, i, PendingIntent.FLAG_UPDATE_CURRENT);
				am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 600000, pi);
			}
		}
	}

	private boolean isNetOkWithNotification() {
		if (FoneUtil.isNetOkWithToast(ApplicationManage.getGlobalContext())) {
			L.v(TAG, "isNetOkWithNotification : true ");
			return true;
		}
			L.v(TAG, "isNetOkWithNotification : false ");
		if (ActivityQueue.getSize() < 1 || !FoneUtil.isAppOnForeground(ApplicationManage.getGlobalContext())) { // 没起应用
			L.v(TAG, "isAppOnForeground : false ");
			FoneUtil.wakeUpfromBackground(SplashActivity.class, null);
		}
		return false;
	}

	/**
	 * 通知服务已经开启返回true，否则返回false
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isServiceStarted(Context context) {
		boolean isRunning = false;
		L.v(TAG, "isStarted", "Check Download Service");
		String className = NotificationService.class.getName();
		ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningServiceInfo> serviceList = activityManager.getRunningServices(Integer.MAX_VALUE);

		for (int i = 0; !isRunning && i < serviceList.size(); i++) {
			RunningServiceInfo serviceInfo = serviceList.get(i);
			ComponentName serviceName = serviceInfo.service;

			if (serviceName.getClassName().equals(className)) {
				isRunning = true;
			}
		}

		L.v(TAG, "isStarted NotificationService is running ", String.valueOf(isRunning));
		return isRunning;
	}
}
